package org.tools.string;

import java.util.Iterator;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/** 
 * 字符串格式化类，format开头的方法，支持 ${..} 占位符；replace开头的方法支持 {...} 占位符
 *
 * <pre> 
 * 构建组：e-tools
 * 作者：eddy
 * 邮箱：1546077710@qq.com
 * 日期：2017年4月23日-下午5:43:28
 * 版权：E源时代
 * </pre>
 */
public class StringFormater {
	
	/**
	 * 格式化带参数的字符串，如 /param/detail.ht?a=${0}&b=${1}
	 * 注意字符串的参数从0下标开始，字符串的参数数量和args数组的数量要一致。
	 * 
	 * @param contentWithNumberPlaceHolder
	 * @param numberReplaceParams
	 * @return
	 */
	public static String format(String contentWithNumberPlaceHolder, Object... numberReplaceParams) {
		for (int i = 0; i < numberReplaceParams.length; i++) {
			contentWithNumberPlaceHolder = contentWithNumberPlaceHolder.replace("${" + i + "}",
					numberReplaceParams[i].toString());
		}
		return contentWithNumberPlaceHolder;
	}

	/**
	 * 格式化如下字符串 http://www.bac.com?a=${a}&b=${b}
	 * 
	 * @param contentWithKeyPlaceHolder
	 * @param keyReplaceParams
	 */
	public static String formatByMap(String contentWithKeyPlaceHolder, Map<String, String> keyReplaceParams) {
		String result = contentWithKeyPlaceHolder;
		if (keyReplaceParams == null || keyReplaceParams.isEmpty())
			return result;
		Iterator<String> keyIts = keyReplaceParams.keySet().iterator();
		while (keyIts.hasNext()) {
			String key = keyIts.next();
			Object value = keyReplaceParams.get(key);
			if (value != null) {
				result = result.replace("${" + key + "}", value.toString());
			}
		}
		return result;
	}

	/**
	 * 将对象转成格式化的字符串输出
	 * 
	 * @param obj
	 *            任意对象
	 * @param isFormatWithQuote
	 *            是否加中括号将结果括起来
	 * @return
	 */
	public static String formatWithQuote(Object obj, boolean isFormatWithQuote) {
		StringBuilder sb = new StringBuilder();
		if (obj == null) {
			sb.append("NULL");
		} else {
			if (obj instanceof Object[]) {
				for (int i = 0; i < ((Object[]) obj).length; i++) {
					sb.append(((Object[]) obj)[i]).append(", ");
				}
				if (sb.length() > 0) {
					sb.delete(sb.length() - 2, sb.length());
				}
			} else {
				sb.append(obj.toString());
			}
		}
		if (isFormatWithQuote && sb.length() > 0 && !((sb.charAt(0) == '[' && sb.charAt(sb.length() - 1) == ']')
				|| (sb.charAt(0) == '{' && sb.charAt(sb.length() - 1) == '}'))) {
			sb.insert(0, "[").append("]");
		}
		return sb.toString();
	}

	/**
	 * 将content中所有{...}的替换为replace参数内容
	 * 
	 * @param contentWithBraces
	 *            待替换的字符串
	 * @param replaceContent
	 *            替换的字符串
	 * @return 替换后的字符串，如content=abc{aa}{bb} ； replace ="ff"，结果就是abcffff
	 */
	public static String replace(String contentWithBraces, String replaceContent) {
		return replace(contentWithBraces, replaceContent, "\\{(.*?)\\}");
	}

	/**
	 * 将content中所有符合regular正则表达式的内容替换为replace参数内容
	 * 
	 * @param contentWithBraces
	 *            待替换的字符串
	 * @param replaceContent
	 *            替换的字符串
	 * @param regularCompare
	 *            正则表达式
	 * @return 替换后的字符串。 如content=abc{aa}{bb} ； replace
	 *         ="ff"，regular="\\{(.*?)\\}"；结果就是abcffff
	 */
	public static String replace(String contentWithBraces, String replaceContent, String regularCompare) {
		Pattern regex = Pattern.compile(regularCompare);
		String result = contentWithBraces;
		Matcher regexMatcher = regex.matcher(result);
		while (regexMatcher.find()) {
			String toReplace = regexMatcher.group(0);
			result = result.replace(toReplace, replaceContent);
			regexMatcher = regex.matcher(result);
		}
		return result;
	}

	/**
	 * 对传入的字符串（content）进行变量值替换（map） 采用默认的正则表达式：\\{(.*?)\\}
	 * 
	 * @param contentWithBraces
	 *            要处理的字符串
	 * @param replaceParamMap
	 *            替换参数和值的集合
	 * @return 替换后的字符串
	 * @throws Exception
	 */
	public static String replaceByMap(String contentWithBraces, Map<String, String> replaceParamMap) {
		return replaceByMap(contentWithBraces, replaceParamMap, "\\{(.*?)\\}");
	}

	/**
	 * 
	 * @param contentWithBraces
	 *            要处理的字符串
	 * @param replaceParamMap
	 *            替换参数和值的集合
	 * @param regularCompare
	 *            正则表达式
	 * @return 替换后的字符串
	 * @throws Exception
	 *             如果template的某个
	 */
	public static String replaceByMap(String contentWithBraces, Map<String, String> replaceParamMap,
			String regularCompare) {
		Pattern regex = Pattern.compile(regularCompare);
		Matcher regexMatcher = regex.matcher(contentWithBraces);
		while (regexMatcher.find()) {
			String key = regexMatcher.group(1);
			String toReplace = regexMatcher.group(0);
			String value = (String) replaceParamMap.get(key);
			if (value != null) {
				contentWithBraces = contentWithBraces.replace(toReplace, value);
			}
		}

		return contentWithBraces;
	}
}
